﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Google.GData.Calendar;
using Google.GData.Client;
using Google.GData.Extensions;

namespace Obsady
{
    class CGoogleCalendar
    {
        const string kMailsFilename = "..\\..\\data\\mails.mls";
        private List<ILogger> _log;
        string _userName = "wzkosz.leszno";
        string _userPassword = "wzkosz.leszno1";
        string _feedUri = "https://www.google.com/calendar/feeds/default/private/full"; // for working with your primary calendar
        string _calEventsUrl = "https://www.googleapis.com/calendar/v3/calendars/calendarId/events"; // 
        CalendarService service = new CalendarService("exampleCo-exampleApp-1");
       
        Dictionary<string, string> mails = new Dictionary<string, string>(); 

        public CGoogleCalendar(List<ILogger> loggers, string userName, string userPassword)
        {
            _userName = userName;
            _userPassword = userPassword;
            _log = loggers;
            service.setUserCredentials(_userName, _userPassword);
            parseMails(mails);
            _log[0].Log(this,"CGoogleCalendar - constructor");
            _log[0].Log(this, "CGoogleCalendar - username " + _userName);
            _log[0].Log(this, "CGoogleCalendar - userPassword " + _userPassword);

        }

        private void log(string str)
        {
            foreach (ILogger log in _log)
            {
                log.Log(this,str);
            }
        }
        
        public EventEntry CreateEvent(CMatch aMatch)
        {
            DateTime date = new DateTime();
            if (-1 == aMatch._data.IndexOf('.'))
            {
                date = DateTime.FromOADate(double.Parse(aMatch._data));
                log("Tworzenie meczu: " + date.ToShortDateString() + aMatch._godz + aMatch.getContent());
            }
            else
            {
                log("Tworzenie meczu: " + aMatch._data + aMatch._godz + aMatch.getContent());              
            }
                      
            EventEntry entry = new EventEntry();

            // Set the title and content of the entry.
            entry.Title.Text = aMatch.getTitle();
            entry.Content.Content = aMatch.getContent();
            
            // Set a location for the event.
            Where eventLocation = new Where();
            eventLocation.ValueString = aMatch.getLocation();
            entry.Locations.Add(eventLocation);

            // If a recurrence was requested, add it.  Otherwise, set the
            // time (the current date and time) and duration (120 minutes)
            // of the event.
                       
            When eventTime = new When();                        
            eventTime.StartTime = parseDate(aMatch._data,aMatch._godz);
            eventTime.EndTime = eventTime.StartTime.AddHours(2);
            entry.Times.Add(eventTime);

            
            // The indexer throws an exception if the requested key is
            // not in the dictionary.

            foreach (KeyValuePair<string, string> referee in aMatch._referees)
            {
                try
                {
                    Who who = new Who();
                    who.ValueString = mails[referee.Value];
                    who.Rel = "http://schemas.google.com/g/2005#home";
                    entry.Participants.Add(who);
                }
                catch (KeyNotFoundException)
                {
                    if ("-" != referee.Value && "" != referee.Value)
                    {
                        log("nie podano adresu email - " + referee.Value);
                    }
                }
            }

            _log[0].Log(this, "CreateEvent before service.Insert");   
            // Send the request and receive the response:
            AtomEntry insertedEntry = null;
            try
            {
                Uri postUri = new Uri(_feedUri);
                insertedEntry = service.Insert(postUri, entry);
                
            }
            catch (Exception e)
            {
                _log[0].Log(this, e.Message.ToString());
            }
            log("OK!");
            return (EventEntry)insertedEntry;                      
        }

        public void getAllEventsFromCalendar()
        {
            string url = "https://www.google.com/calendar/feeds/wzkosz.leszno@gmail.com/private/full";

            EventQuery myQuery = new EventQuery(url);
            myQuery.StartTime = new DateTime(2011, 12, 1);
            myQuery.EndTime = new DateTime(2011, 12, 2);

            EventFeed myResultsFeed = service.Query(myQuery);
        }

        private DateTime parseDate(string aDate,string aTime)
        {            
            _log[0].Log(this, "parseDate - started ");
            DateTime date;                      
            if (-1 != aDate.IndexOf('.'))
            {
                int day = int.Parse(aDate.Substring(0, 2));
                int month = int.Parse(aDate.Substring(3, 2));
                int year = int.Parse(aDate.Substring(6, 4));
                int hour = int.Parse(aTime.Substring(0, 2));
                int min = int.Parse(aTime.Substring(3, 2));
                date = new DateTime(year, month, day, hour, min, 0);
            }
            else
            {                
                date = new DateTime();                
                date = DateTime.FromOADate(double.Parse(aDate));
                date = date.AddHours(int.Parse(aTime.Substring(0, 2)));
                date = date.AddMinutes(int.Parse(aTime.Substring(3, 2)));
            }
            _log[0].Log(this, "parseDate  - end");
            return date;
            
        }

        private void parseMails(Dictionary<string, string> aMails)
        {
       
            StreamReader streamReader = new StreamReader(kMailsFilename, Encoding.Default);
            string str;
            while ((str = streamReader.ReadLine()) != null)
            {
                int pos = 0;
                int last = 0;
                pos = str.IndexOf(" ", 0);
                if (pos != -1)
                {
                    String buf1 = str.Substring(last, pos - last);
                    last = pos++;
                    String buf2 = str.Substring(last, str.Length - last);
                    buf1 = buf1.Trim();
                    buf2 = buf2.Trim();
                    aMails.Add(buf1, buf2);
                }
            }
            streamReader.Close();
        }
    }
}
